package com.open.demo.mvvm.engine

import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProviders
import java.lang.reflect.ParameterizedType

/**
 *
 * @Author: hailong.qiu 356752238@qq.com
 * @Maintainer: hailong.qiu 356752238@qq.com
 * @Date: 2022/2/25
 * @Copyright: 2022 www.andriodtvdev.com Inc. All rights reserved.
 */
abstract class BaseFragment<VM:BaseViewModel> : Fragment() {
    protected lateinit var viewModel:VM

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        createViewModel()
    }

    private fun createViewModel() {
        val type = javaClass.genericSuperclass
        if (type is ParameterizedType) {
            val tp = type.actualTypeArguments[0]
            val tClass = tp as? Class<VM> ?: BaseViewModel::class.java
            //
            viewModel = ViewModelProviders.of(this).get(tClass) as VM
//            viewModel = ViewModelProvider(viewModelStore, ViewModelProvider.NewInstanceFactory())
//                .get(tClass) as VM
        }
    }

}